package com.infra.micro.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.infra.common.resp.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

/**
 * @author PD
 */
public abstract class BaseFilter {
    protected static final Logger LOGGER = LoggerFactory.getLogger(BaseFilter.class);

    /**
     * build response
     *
     * @param response
     * @param res
     * @return
     */
    protected Mono<Void> buildResponse(ServerHttpResponse response, Response res) {
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            return bufferFactory.wrap(JSON.toJSONBytes(res));
        }));
    }
}
